package org.ws.task.common;

import io.netty.channel.Channel;
import org.apache.commons.lang.StringUtils;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

public final class AddressUtils {

    private AddressUtils(){}

    private static final String UNKNOWN = "UNKNOWN";

    public static String getStringSocketAddress(final SocketAddress socketAddress){
        if(socketAddress == null){
            return UNKNOWN;
        }
        String address = socketAddress.toString();
        if(StringUtils.isBlank(address)){
            return UNKNOWN;
        }
        return address.substring(1);
    }

    public static String getChannelRemoteAddress(final Channel channel){
        if(channel == null){
            return UNKNOWN;
        }
        SocketAddress remoteAddress = channel.remoteAddress();
        if(remoteAddress == null){
            return UNKNOWN;
        }
        String address = remoteAddress.toString();
        if(StringUtils.isBlank(address)){
            return UNKNOWN;
        }
        int index = address.lastIndexOf('/');
        if(index >= 0){
            return address.substring(index + 1);
        }
        else {
            return address;
        }
    }

    public static SocketAddress convertSocketAddress(final String address) {
        int split = address.lastIndexOf(':');
        String host = address.substring(0, split);
        String port = address.substring(split + 1);
        return new InetSocketAddress(host, Integer.parseInt(port));
    }

    public static int parsePort(final String address){
        int split = address.lastIndexOf(':');
        return Integer.parseInt(address.substring(split + 1));
    }
}
